const axios = require('axios');

(async () => {
  console.log('🔍 测试勋章筛选功能');
  
  try {
    // 1. 登录用户
    const loginResponse = await axios.post('http://localhost:3000/api/auth/login', {
      email: 'admin@campus.com',
      password: 'admin123'
    });
    
    const authToken = loginResponse.data.token;
    const userId = loginResponse.data.user.id;
    console.log(`✅ 用户登录成功: ID=${userId}`);
    
    // 2. 测试三种筛选模式
    console.log('\n🏆 测试勋章筛选模式...');
    
    // 测试 "全部勋章" (all)
    const allBadgesResponse = await axios.get('http://localhost:3000/api/badges', {
      headers: { Authorization: `Bearer ${authToken}` }
    });
    console.log(`📊 全部勋章: ${allBadgesResponse.data.badges.length}个`);
    
    // 测试 "我的勋章" (owned) 
    const ownedBadgesResponse = await axios.get('http://localhost:3000/api/badges?filter=owned', {
      headers: { Authorization: `Bearer ${authToken}` }
    });
    console.log(`🎖️ 我的勋章: ${ownedBadgesResponse.data.badges.length}个`);
    
    // 测试 "可获得勋章" (available)
    const availableBadgesResponse = await axios.get('http://localhost:3000/api/badges?filter=available', {
      headers: { Authorization: `Bearer ${authToken}` }
    });
    console.log(`🔓 可获得勋章: ${availableBadgesResponse.data.badges.length}个`);
    
    // 3. 验证数据一致性
    console.log('\n🔍 验证数据一致性:');
    
    const ownedCount = ownedBadgesResponse.data.badges.length;
    const availableCount = availableBadgesResponse.data.badges.length;
    const totalCount = allBadgesResponse.data.badges.length;
    
    console.log(`已获得勋章: ${ownedCount}`);
    console.log(`可获得勋章: ${availableCount}`);
    console.log(`全部勋章: ${totalCount}`);
    console.log(`预期: ${ownedCount} + ${availableCount} = ${totalCount}`);
    
    if (ownedCount + availableCount === totalCount) {
      console.log('✅ 数据一致性验证通过');
    } else {
      console.log('❌ 数据一致性验证失败');
    }
    
    // 4. 检查勋章状态分布
    console.log('\n📋 勋章状态分析:');
    
    // 分析"全部勋章"中的状态分布
    let ownedInAll = 0;
    let availableInAll = 0;
    
    allBadgesResponse.data.badges.forEach(badge => {
      if (badge.isOwned || (badge.status === 'minted' && badge.user_id === userId)) {
        ownedInAll++;
      } else if (badge.status === 'available') {
        availableInAll++;
      }
    });
    
    console.log(`全部勋章中 - 已获得: ${ownedInAll}, 可获得: ${availableInAll}`);
    
    // 检查"我的勋章"中是否都是已获得的
    const allOwnedValid = ownedBadgesResponse.data.badges.every(badge => 
      badge.isOwned || (badge.status === 'minted' && badge.user_id === userId)
    );
    console.log(`我的勋章全部为已获得: ${allOwnedValid ? '✅' : '❌'}`);
    
    // 检查"可获得勋章"中是否都是未获得的
    const allAvailableValid = availableBadgesResponse.data.badges.every(badge => 
      badge.status === 'available' && !badge.isOwned
    );
    console.log(`可获得勋章全部为未获得: ${allAvailableValid ? '✅' : '❌'}`);
    
    // 5. 显示示例勋章
    console.log('\n📝 勋章示例:');
    
    if (ownedBadgesResponse.data.badges.length > 0) {
      const ownedExample = ownedBadgesResponse.data.badges[0];
      console.log('已获得勋章示例:');
      console.log(`  名称: ${ownedExample.badge_name}`);
      console.log(`  状态: ${ownedExample.status}`);
      console.log(`  是否拥有: ${ownedExample.isOwned ? '✅' : '❌'}`);
    }
    
    if (availableBadgesResponse.data.badges.length > 0) {
      const availableExample = availableBadgesResponse.data.badges[0];
      console.log('可获得勋章示例:');
      console.log(`  名称: ${availableExample.badge_name}`);
      console.log(`  状态: ${availableExample.status}`);
      console.log(`  是否拥有: ${availableExample.isOwned ? '✅' : '❌'}`);
    }
    
    // 6. 详细检查"我的勋章"数据
    console.log('\n🔎 详细检查"我的勋章"数据:');
    if (ownedBadgesResponse.data.badges.length > 0) {
      const invalidOwnedBadges = ownedBadgesResponse.data.badges.filter(badge => 
        !(badge.isOwned || (badge.status === 'minted' && badge.user_id === userId))
      );
      
      if (invalidOwnedBadges.length > 0) {
        console.log(`❌ 发现 ${invalidOwnedBadges.length} 个不符合"已获得"条件的勋章`);
        invalidOwnedBadges.forEach((badge, index) => {
          console.log(`问题勋章 ${index + 1}: ${badge.badge_name}`);
          console.log(`  状态: ${badge.status}, 用户ID: ${badge.user_id}, isOwned: ${badge.isOwned}`);
        });
      } else {
        console.log('✅ "我的勋章"中的所有勋章都正确标记为已获得');
      }
    } else {
      console.log('⚠️ 无法检查：用户没有任何已获得的勋章');
    }
    
    // 7. 详细检查"可获得勋章"数据
    console.log('\n🔎 详细检查"可获得勋章"数据:');
    if (availableBadgesResponse.data.badges.length > 0) {
      const invalidAvailableBadges = availableBadgesResponse.data.badges.filter(badge => 
        badge.isOwned || badge.status !== 'available'
      );
      
      if (invalidAvailableBadges.length > 0) {
        console.log(`❌ 发现 ${invalidAvailableBadges.length} 个不符合"可获得"条件的勋章`);
        invalidAvailableBadges.forEach((badge, index) => {
          console.log(`问题勋章 ${index + 1}: ${badge.badge_name}`);
          console.log(`  状态: ${badge.status}, isOwned: ${badge.isOwned}`);
        });
      } else {
        console.log('✅ "可获得勋章"中的所有勋章都正确标记为未获得');
      }
    } else {
      console.log('⚠️ 无法检查：没有可获得的勋章');
    }
    
    console.log('\n🎯 筛选功能总结:');
    console.log('✅ "全部勋章": 显示所有勋章（已获得+未获得）');
    console.log('✅ "我的勋章": 只显示已获得的勋章');
    console.log('✅ "可获得勋章": 只显示未获得的勋章');
    
  } catch (error) {
    console.error('❌ 测试失败:', error.message);
    if (error.response) {
      console.error('详细错误:', error.response.data);
    }
  }
})(); 